<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateBtn">添加分类</el-button>
        </el-col>
      </el-row>
 <!-- element-ui没有此样式的表格，需要引入其它插件作表格
      show-index索引号，index-text索引号的名称，selection-type复选框，
      expand-type展开,border纵向边框,show-row-hover高亮 -->
      <tree-table class="tree-table"
        :data="cateList" 
        :columns="columns"
        :show-index="true"
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        border
        :show-row-hover="false">
        <!-- 是否有效列 -->
        <template slot="isok" slot-scope="scope">
          <i 
            class="el-icon-success" 
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen">
          </i>
          <i 
            class="el-icon-error" 
            v-else
            style="color: red">
          </i>
        </template>
        <!-- 排序列 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作列 -->
        <template slot="opt" slot-scope="scope">
          <el-button 
            type="primary" 
            icon="el-icon-edit"
            size="mini"
            @click="editCateBtn(scope.row)">编辑</el-button>
          <el-button 
            type="danger" 
            icon="el-icon-delete"
            size="mini"
            @click="deleteBtn(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="cateDialogVisible"
      width="45%"
      @close="cateClose">
      <el-form :model="cateForm" :rules="cateRules" ref="cateRef" label-width="100px">
        <el-form-item label="分类名称 :" prop="cat_name">
          <el-input v-model="cateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- options是级联选择器的数据来源,props配置对象，v-model选中的父级分类的id -->
          <el-cascader     
            :options="parentCateList"
            :props="cascaderProps"           
            v-model="selectKeys"
            @change="parentCateChange"
            clearable>
          </el-cascader>
        </el-form-item> 
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

     <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="45%"
      @close="editClose">
      <el-form :model="editForm" :rules="editRules" ref="editRef" label-width="100px">
        <el-form-item label="分类名称 :" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name:'Cate',
  data() {
    return {
      // 商品分类的数据列表
      cateList:[],
      queryInfo:{
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total:0,
      // 为tree-table表格指定列的定义
      columns:[
        {label:"分类名称", prop:"cat_name"},
        {
          label:"是否有效",
          // 将当前列自定义为模板列
          type:"template",
          // 模板名称
          template:"isok"
        },
        {label:"排序", type:"template", template:"order"},
        {label:"操作", type:"template", template:"opt"},
      ],
      cateDialogVisible: false,
      // 添加分类的表单数据
      cateForm:{
        cat_name:'',
        // 父级分类id
        cat_pid: 0,
        // 分类层级,0表示默认一级分类
        cat_level: 0,
      },
      cateRules:{
        cat_name:[
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 父级分类的列表
      parentCateList:[],
      // 级联选择器的配置对象
      cascaderProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        // 次级菜单展开方式
        expandTrigger: 'hover',
        // 是否可选择上一级菜单
        checkStrictly: 'true'
      },
      // 以数组形式包含选中的父级分类的id
      selectKeys:[],
      // 控制编辑对话框的展示与隐藏
      editDialogVisible: false,
      // 编辑分类对话框的数据
      editForm:{},
      editRules:{
        cat_name:[
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created(){
    this.getCateList()
  },
  methods:{
    async getCateList(){
      const {data:res} = await this.$http.get('categories',{params: this.queryInfo})
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.pagenum = res.data.pagenum
      this.pagesiaze = res.data.pagesize
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // pagesize改变时调用此函数
    handleSizeChange(value){
      this.queryInfo.pagesize = value
      this.getCateList()
    },
    // pagenum改变时调用此函数
    handleCurrentChange(value){
      this.queryInfo.pagenum = value
      this.getCateList()
    },
    // 添加分类按钮展示对话框
    async addCateBtn(){
      this.getParentCateList()
      this.cateDialogVisible = true
    },
    // 获取父级分类的列表
    async getParentCateList(){
      const {data:res} = await this.$http.get('categories',{params:{type:2} })
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('获取父级分类失败')
      this.parentCateList = res.data
    },
    // 父级分类选择项发生变化时触发此函数
    parentCateChange(){
      //console.log(this.selectKeys);
      // 若selectKeys数组的长度大于0，表明选择了父级分类
      if(this.selectKeys.length > 0) {
        // 将selectKeys数组里的最后一个id赋值给表单添加分类的id
        this.cateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        // selectKeys的长度等于表单的添加分类的等级（排序）
        this.cateForm.cat_level = this.selectKeys.length
      } else {
        // 没有选择父级分类，父级分类的等级和id还是为0
        this.cateForm.cat_pid = 0
        this.cateForm.cat_level = 0
      }
    },
    // 点击对话框的确定按钮，添加分类
    addCate(){
      //console.log(this.cateForm)
      this.$refs.cateRef.validate( async value => {
        if(!value) return 
        const {data:res} = await this.$http.post('categories',this.cateForm)
        //console.log(res)
        if(res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateList()
        this.cateDialogVisible = false
      })
    },
    // 关闭对话框，重置对话框的所有数据
    cateClose(){
      this.$refs.cateRef.resetFields()
      this.cateForm.cat_pid = 0
      this.cateForm.cat_level = 0
      this.selectKeys = []
    },
    // 编辑分类根据id查询分类
    async editCateBtn(cate){
      const {data:res} = await this.$http.get('categories/' + cate.cat_id)
      //console.log(res)
      this.editForm = res.data
      console.log(this.editForm);
      this.editDialogVisible = true
    },
    // 点击确定按钮编辑分类
    editDialog(){
      this.$refs.editRef.validate( async value => {
        if(!value) return
        const {data:res} = await this.$http.put('categories/' + this.editForm.cat_id, 
        {cat_name:this.editForm.cat_name})
        //console.log(res)
        if(res.meta.status !== 200) return this.$message.error('编辑分类失败')
        this.$message.success('编辑分类成功')
        this.getCateList()
        this.editDialogVisible = false
      })
    },
    // 关闭编辑分类对话框
    editClose(){
      this.$refs.editRef.resetFields()
      this.editDialogVisible = false
    },
    // 删除分类
    async deleteBtn(cate){
      const result = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).catch(error => error)
      if(result !== 'confirm') return this.$message.info('已取消删除')
      const {data:res} = await this.$http.delete('categories/' + cate.cat_id)
      if(res.meta.status !== 200) return this.$message.error('删除分类失败')
      this.$message.success('删除分类成功')
      this.getCateList()
    },
  }
}
</script>

<style lang="less" scoped>
div /deep/ .el-card{
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-top: 20px;

  .tree-table{
   margin: 20px 0;
  }
}
 .el-cascader {
   width: 100%;
 }
</style>